<?php

/**
 * This is the model class for table "{{account}}".
 *
 * The followings are the available columns in table '{{account}}':
 * @property integer $id
 * @property string $name
 * @property string $display_name
 * @property string $contact_number
 * @property string $mobile_number
 * @property string $fax_number
 * @property string $email
 * @property string $web_url
 * @property string $category_id
 * @property integer $type_code
 * @property integer $status_code
 * @property string $create_tie
 * @property string $create_timestamp
 * @property string $create_datetime
 * @property strign $create_date
 * @property string $create_time
 * @property integer $create_by
 * @property string $update_timezone
 * @property string $update_timestamp
 * @property string $update_datetime
 * @property string $update_date
 * @property string $update_time
 * @property integer $update_by
 */
class Account extends ActiveRecord {
    
    public $name_;
    public $displayName_;
    
    public $contactNumber_;
    public $mobileNumber_;
    public $faxNumber_;
    public $email_;
    public $url_;
    
    public $country_;
    public $type_;
    public $categoryId_;
    public $status_;
    
    private $_jsonFile='account';
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Account the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{account}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(            
            array('name_, displayName_, contactNumber_, faxNumber_, email_, url_, type_, status_', 'filter', 'filter'=>'trim'),
            //array('name_, displayName_, ','filter','filter'=>array($obj=new CHtmlPurifier(),'purify')),
            
            // custom rules
            array('name_, displayName_, email_, mobileNumber_', 'required', 'on'=>'userUpdate, adminCreate, adminUpdate'),
            array('name_', 'length', 'max'=>255),
            array('name_', 'unique', 'attributeName'=>'name', 'allowEmpty'=>false, 'caseSensitive'=>false, 'className'=> get_class($this), 'on'=>'userUpdate, adminCreate, adminUpdate'),
            array('displayName_', 'length', 'max'=>20),
            array('displayName_', 'ext.validators.AlphaNumericValidator', 'on'=>'adminCreate, adminUpdate, userUpdate'),

            array('contactNumber_, faxNumber_, mobileNumber_','length','max'=>15, 'min'=>3),
            array('contactNumber_, faxNumber_, mobileNumber_', 'ext.validators.ContactNumberValidator'),
            
            array('email_', 'length', 'max' => 50),
            array('email_', 'email', 'checkMX' => false),
            
            array('url_', 'url', 'defaultScheme'=>'http'),
            array('type_', 'in', 'range'=>array_keys($this->typeOption), 'allowEmpty'=>false),
            
            array('id_, name_, displayName_, contactNumber_, faxNumber_, email_, url_, categoryId_', 'safe', 'on'=>'adminSearch, userUpdate, adminCreate, adminUpdate'),            
            array('status_','safe', 'on'=>'adminCreate, adminUpdate'),
            
            // logo rules
            array('image_', 'file', 'types' => 'jpg,gif,png', 'allowEmpty' => true, 'on' => 'userUpdate, adminCreate, adminUpdate'),

            // must include
            array('status_', 'in', 'range'=>array_keys($this->statusOption), 'allowEmpty'=>false),
            
            array('var_', 'ext.validators.BotDetectionValidator'),
            array('var_', 'safe'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            // must included
            'creator' => array(self::BELONGS_TO, 'User', 'create_by'),
            'editor' => array(self::BELONGS_TO, 'User', 'update_by'),
            
            // custom
            'html' => array(self::HAS_ONE, 'Content', 'module_id', 'scopes' => array('module' => __CLASS__, 'language' => $this->defaultLanguage)),
            'photo' => array(self::HAS_ONE, 'Gallery', 'module_id', 'scopes' => array('module' => __CLASS__, 'primary', 'accessible')),
            'address'=> array(self::HAS_ONE, 'Address', 'module_id', 'scopes'=>array('module'=>__CLASS__, 'primary', 'accessible')),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'image_'=>Lang::t('account.lbl.logo'),
            'name_'=>Lang::t('account.lbl.name'),
            'displayName_'=>Lang::t('account.lbl.display.name'),
            
            'content_'=>Lang::t('account.lbl.description'),
            'sefUrl_' => Lang::t('account.lbl.sef.url'),
            'metaTitle_' => Lang::t('account.lbl.meta.title'),
            'metaDescription_' => Lang::t('account.lbl.meta.description'),
            'metaKeywords_' => Lang::t('account.lbl.meta.keywords'),            
            
            'buildingName_'=>Lang::t('account.lbl.building.name'),
            'address_'=>Lang::t('account.lbl.address'),
            'street_'=>Lang::t('account.lbl.street'),
            'district_'=>Lang::t('account.lbl.district'),
            'city_'=>Lang::t('account.lbl.city'),
            'province_'=>Lang::t('account.lbl.province'),
            'typeNumber_'=>Lang::t('account.lbl.type.number'),
            'locality_'=>Lang::t('account.lbl.locality'),
            'state_'=>Lang::t('account.lbl.state'),
            'postalCode_'=>Lang::t('account.lbl.postal.code'),
            'country_'=>Lang::t('account.lbl.country'),
            'latitude_'=> Lang::t('account.lbl.latitude'),
            'longitude_'=> Lang::t('account.lbl.longitude'),
            
            'contactNumber_'=>Lang::t('account.lbl.contact.number'),
            'faxNumber_'=>Lang::t('account.lbl.fax.number'),
            'email_'=>Lang::t('account.lbl.email'),
            'url_'=>Lang::t('account.lbl.url'),
            
            'type_'=>Lang::t('account.lbl.type'),
            'status_'=>Lang::t('account.lbl.status'),
        );
    }
    
    public function scopes() {
        $t=$this->getTableAlias(false);
        return array(
            'published' => array(
                'condition' => $t.'.status_code = :activeStatus'.$t,
                'params' => array(
                    ':activeStatus'.$t => Option::STATUS_ACTIVE,
                ),
            ),
            'accessible'=>array(
                'condition' => $t.'.status_code <> :deletedStatus'.$t,
                'params' => array(
                    ':deletedStatus'.$t=>Option::STATUS_DELETED,
                ),
            ),
        );
    }
    
    public function autoFill(){
        switch($this->scenario){
            case 'adminCreate':
                $this->type_=Option::USER_ROLE_MERCHANT;
                $this->country_ = Yii::app()->controller->countryCode;
                break;
            
            case 'update':
            case 'adminUpdate':
            case 'userUpdate':
                $this->name_=$this->name;
                $this->displayName_=$this->display_name;
                $this->status_=(int)$this->status_code;
                $this->type_=(int)$this->type_code;
                $this->contactNumber_=$this->contact_number;
                $this->mobileNumber_=$this->mobile_number;
                $this->faxNumber_=$this->fax_number;
                $this->email_=$this->email;
                $this->url_=$this->web_url;
                $this->categoryId_=array_filter(explode(',',$this->category_id));
                break;
        }
    }
    
    protected function beforeSave(){
        if(parent::beforeSave()){
            
            if(in_array($this->scenario, array('adminCreate', 'adminUpdate'))){
                $this->status_code=$this->status_;
                $this->type_code=$this->type_;
            }
            
            if(in_array($this->scenario, array('adminCreate', 'adminUpdate', 'userUpdate'))){
                $this->name=$this->name_;
                $this->display_name=$this->displayName_;
                $this->contact_number=$this->contactNumber_;
                $this->mobile_number=$this->mobileNumber_;
                $this->fax_number=$this->faxNumber_;
                $this->email=$this->email_;
                $this->web_url=$this->url_;
                $this->category_id=is_array($this->categoryId_)? implode(',', $this->categoryId_):$this->categoryId_;
            }
            
            if ($this->isNewRecord) {
            	$this->setCreateDateTime();
            } else {
            	$this->setUpdateDateTime();
            }
            return true;
        }else
            return false;
    }        
        
    public function updateRecord(){
        $this->beginTransaction();
        try{
            if($this->save(false)){
                $this->dataLog[get_class($this)]=$this->attributes;
                $this->updateDependentModel(func_get_args());
                if($this->image_) $this->uploadImages('image_');
                $this->updateUsersStatus();
            }
            if($this->hasErrors()){
                $this->rollback();
                return false;
            }else{
                $this->commit();
                $this->saveLog();
                User::model()->updateAllRoleByAccount($this->id, $this->type_code);
                return true;
            }
        } catch (Exception $e){
            $this->rollback();
        }
    }
        
    public function updateUsersStatus(){
        return User::model()->updateByAccountStatus($this->id, $this->status_code);
    }    
    
    public function updateJson(){

        $data=$this->readJsonFile($this->_jsonFile);
        if(!$data) $data=array();
        
        $data[$this->id]=array(
            'name'=>$this->businessName,
            'displayName'=>$this->displayName,
            'logo'=>$this->logo,
            'web_url'=>$this->web_url,
            'url'=>$this->url,
            'type'=>$this->type_code,
            'status'=>$this->status_code,
        );
        $this->createJsonFile($data, $this->_jsonFile);
    }
    
    public function getStatusOption($id=null){
        return Option::recordStatus($id);
    }
    
    public function getTypeOption($id=null){
        return Option::merchantRole($id);
    }
    
    public function getCategoryOption($id=null){
        return array();
    }
    
    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function userSearch() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.
        $t=$this->getTableAlias(false);
        $criteria = new CDbCriteria;

        $criteria->compare($t.'.id', $this->id_);

        return new ActiveDataProvider($this->published(), array(
            'criteria' => $criteria,
        ));
    }
    
    public function adminSearch(){
        $t=$this->getTableAlias(false);
        $criteria=new CDbCriteria;
        $criteria->with=array(
            /*
            'address2'=>array(
                'joinType'=>'LEFT OUTER JOIN',
                'scopes'=>array(
                    'module'=>get_class($this),
                    'accessible',
                    'countrySearch'=>$this->country_,
                ),
            ),*/
        );
        $criteria->together=true;
        
        $criteria->compare($t.'.id', $this->id_, true);
        $criteria->compare($t.'.name', $this->name_, true);
        $criteria->compare($t.'.contact_number', $this->contactNumber_, true);
        $criteria->compare($t.'.fax_number', $this->faxNumber_, true);
        $criteria->compare($t.'.email', $this->email_, true);
        $criteria->compare($t.'.type_code',$this->type_);
        $criteria->compare($t.'.status_code',$this->status_);
        
        /*
        $address=Address::model();
        $address->module_=get_class($this);
        $address->country_=$this->country_;
        $addressSQL=$address->subQuery();
        */
        
        $criteria->addCondition(array_filter(array(
            //empty($addressSQL) ? null:$t.'.id IN ('.$addressSQL.')',
        )));
        
        return new ActiveDataProvider($this->accessible(), array(
            'criteria' => $criteria,
        ));
    }
    
    public function findAllNameInArray(){
        $records = $this->readJsonFile($this->_jsonFile);
        $option=array();
        if(empty($records)){
            foreach ($this->published()->findAll() as $data) {
                $option[$data->id] = $data->businessName;
            }
        }else{
            foreach($records as $id=>$data){
                $option[$id]=$data['name'];
            }
        }
        asort($option);
        return $option;
    }
    
    public function getSquareLogo(){
        return $this->squareThumbnail;
    }
    
    public function getlargeSquareLogo(){
        return $this->largeSquareThumbnail;
    }
    
    public function getLogo(){
        return $this->thumbnail;
    }
    
    public function getSmallLogo(){
        return $this->smallThumbnail;
    }
    
    public function getMediumLogo(){
        return $this->mediumThumbnail;
    }
    
    public function getOriginalLogo(){
        return $this->originalFile;
    }
    
    public function getBusinessName(){
        return $this->name;
    }
    
    public function getDisplayName(){
        return $this->display_name;
    }
    
    public function getContactNumber(){
        return $this->contact_number;
    }
    
    public function getFaxNumber(){
        return $this->fax_number;
    }
    
    public function getContactEmail(){
        return $this->email;
    }
    
    public function getWebUrl(){
        return $this->web_url;
    }
    
    public function getTypeCode(){
        return (int)$this->type_code;
    }
    
    public function getType(){
        return $this->getTypeOption((int)$this->type_code);
    }
    
    public function getUrl(){
        switch($this->scenario){
            case 'userUpdate':
                return Yii::app()->createAbsoluteUrl('account/profile/view', array(
                    'accountId'=>$this->id,
                    'accountName'=>$this->sefUrl,
                ));
                break;
            case 'userSearch':
            default:
                return Yii::app()->createAbsoluteUrl('account/site/view', array(
                    'id'=>$this->id,
                    'accountName'=>$this->sefUrl,
                ));
                break;
        }
    }
}